import time
from unittest import expectedFailure

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

from common.Utils import ChatDriver

class HomePageTest:
    url=""
    driver=""
    def __init__(self):
        self.url = "http://127.0.0.1:8080/client.html"
        self.driver = ChatDriver.driver
        self.driver.get(self.url)

    #未登录的状态访问首页
    def unLoggedHomePageTest(self):
        #等待未登录弹窗
        wait = WebDriverWait(self.driver, 2)
        alter = wait.until(expected_conditions.alert_is_present())
        #未登录弹窗，点击确定
        alter.accept()
        #跳转到登录页，查找 “网页聊天”
        text = self.driver.find_element(By.XPATH, "/html/body/div[1]").text
        print(text)
        assert text=="网页聊天"

    #登录状态，测试首页的元素
    def loggedHomePageTest(self):
        # 显式等待10s
        wait = WebDriverWait(self.driver, 20)
        #一开始进入界面时数据还未加载，等待加载完成后代码继续运行
        wait.until(
            expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, "#session-list > li:nth-child(7)"))
        )
        # -------------------通过会话列表，打开与 zhangsan 的聊天窗口--------------
        # 点击会话列表
        session_list = wait.until(
            expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, "body > div.client-container > div > div.left > div.tab > div.tab-session"))
        )
        session_list.click()
        # 点击与 zhangsan 的会话
        zhangsan_session = wait.until(
            expected_conditions.visibility_of_element_located((By.XPATH, "//*[@id=\"session-list\"]/li[7]/h3"))
        )
        zhangsan_session.click()
        print(f'session:{zhangsan_session.text}')
        # 查找消息
        msg = wait.until(
            expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, "body > div.client-container > div > div.right > div.message-show > div:nth-child(1) > div > p"))
        )
        print(f'李四与张三的聊天信息：{msg.text}')

        # ------------通过联系人列表，打开与 zhangsan 的聊天---------------
        # 点击联系人列表
        contact_list = wait.until(
            expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, "body > div.client-container > div > div.left > div.tab > div.tab-friend"))
        )
        contact_list.click()
        # 点击zhangsan
        zhangsan_contact = wait.until(
            expected_conditions.visibility_of_element_located(
                (By.XPATH, "//*[@id=\"friend-list\"]/li/h4"))
        )
        print(f'好友：{zhangsan_contact.text}')
        zhangsan_contact.click()


